<?php
/**
  * 计划任务接口
  */
echo 1;
define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
@ini_set('display_errors',        2);
require(ROOT_PATH . 'includes/lib_wangcang.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/cls_json.php');
$json = new JSON();
/* 任务操作 */
$action  = isset($_REQUEST['act']) ? trim($_REQUEST['act']) : 'default';

/* 推送订单 */
if($action == 'pushtrades'){
    echo '程序开始<br/>';
    // 网仓状态1 订单状态 1已确认         支付是支付宝并已支付 或者 货到付款的
    $sql = "SELECT order_id FROM " . $ecs->table('order_info') . " WHERE wangcangstatus = 0 AND order_status = 1 AND ((pay_id = 1 AND pay_status = 2) OR pay_id = 3) AND agency_id = 3 AND confirm_time <= ".(time()-1800)." ORDER BY add_time DESC";
    $orderIdList = $db->getCol($sql);
    if($orderIdList){
        /* 如果有需要推送的订单，则将其分流，每100单请求推送一次 */
        $j = ceil(count($orderIdList)/100);
        for ($i=0; $i < $j; $i++) {
            $arr[$i] = array_slice($orderIdList, $i*100, 100);
        }
        foreach ($arr as $key => $value) {
            /* 推送订单 */
            $data = vsetpushTrades($value, $v_data);
            $orderIdList = $value;
            /* 如果存在失败 */
            if(!empty($data['data']['failed_list'])){
                foreach ($data['data']['failed_list'] as $key => $value) {
                    $orderSnList[] = $value['order_no'];
                }
                /* 查询失败状态的订单状态 */
                $datas = vgettradeStatusQuery($orderSnList, $v_data);
                foreach ($datas as $key => $value) {
                    /* 如果网仓存在此订单记录，则更新此订单状态 */
                    if(!empty($value['data']['trades']['0']['status'])){
                        $sql = "UPDATE " . $ecs->table('order_info') . " SET wangcangstatus = '". $value['data']['trades']['0']['status'] ."' WHERE order_sn = ".$value['data']['trades']['0']['order_no'];
                        $db->query($sql);
                    }
                    /* 删除更新此订单记录 */
                    $sql = "SELECT order_id FROM " . $ecs->table('order_info') . " WHERE order_sn = '" . $orderSnList[$key] . "'";
                    $order_id = $db->getOne($sql);
                    $keys = array_keys($orderIdList, $order_id);
                    unset($orderIdList[$keys[0]]);
                }
                /* 记录出错日志 */
                $crontab = $data['data']['failed_list'];
                foreach ($crontab as $key => $value) {
                    $crontab[$key]['orderSn'] = $value['order_no'];
                    $crontab[$key]['addTime'] = time();
                    $db->autoExecute($ecs->table('wclogcrontab'), $crontab[$key]);
                }
            }elseif(!empty($data['data']['successs_count'])){
                /* 更新订单记录 */
                foreach ($orderIdList as $key => $value) {
                    $sql = "UPDATE " . $ecs->table('order_info') . " SET wangcangstatus = 130 WHERE order_id = $value";
                    $db->query($sql);
                }
            }
        }
        echo "<br/>程序结束<br/>打印结果<br/><pre>";
        print_r($data);
        echo "</pre>";
        exit;
    }
    echo "<br/>程序结束<br/>打印结果<br/><pre>";
    print_r($orderIdList);
    echo "</pre>";
    exit;
}

/* 推送退货单 */
elseif ($action == 'pushBackTrades'){
    echo '程序开始<br/>';
    $sql = "SELECT return_id FROM " . $ecs->table('order_return_info') . " WHERE is_push = 2 AND area_id = 3";
    $backList = $db->getCol($sql);
    if($backList){
        $data = vsetpushBackTrades($backList, $v_data);
        if(!empty($data['data']['backTrades'])){
            foreach ($data['data']['backTrades'] as $key => $value) {
                if($value['flag'] == 'false'){
                    $crontab['orderSn'] = $value['order_return_no'];
                    $crontab['reason'] = $value['season'];
                    $crontab['addTime'] = time();
                    $crontab['extension'] = 'pushBackTrades';
                    $db->autoExecute($ecs->table('wclogcrontab'), $crontab);
                }elseif($value['flag'] == 'true'){
                    $sql = "UPDATE " . $ecs->table('order_return_info') . " SET is_push = 3 WHERE return_id = $value[order_return_no]";
                    $db->query($sql);
                }
            }
        }
        echo "<br/>程序结束<br/>打印结果<br/><pre>";
        print_r($data);
        echo "</pre>";
        exit;
    }
    echo "<br/>程序结束<br/>打印结果<br/><pre>";
    print_r($data);
    echo "</pre>";
    exit;
}

/* 查询并更新退货单状态 */
elseif ($action == 'updateBackTrades'){
    echo '程序开始<br/>';
    $sql = "SELECT return_id FROM " . $ecs->table('order_return_info') . " WHERE is_push = 3 AND area_id = 3";
    $backList = $db->getCol($sql);
    if($backList){
        $data = vgetbackTradeQuery($backList, $v_data);
        if(!empty($data['data']['backTrades'])){
            foreach ($data['data']['backTrades'] as $key => $value) {
                if($value['order_return_status'] == '3'){
                    $sql = "UPDATE " . $ecs->table('order_return_info') . " SET is_push = 4 WHERE return_id = $value[order_return_no]";
                    $db->query($sql);
                }
            }
        }
        echo "<br/>程序结束<br/>打印结果<br/><pre>";
        print_r($data);
        echo "</pre>";
        exit;
    }
    echo "<br/>程序结束<br/>打印结果<br/><pre>";
    print_r($data);
    echo "</pre>";
    exit;
}

/* 更新库存 */
elseif ($action == 'updateStock'){
    echo '程序开始<br/>';
    /* 获取当前网仓库存记录 */
    $wcgoodsList = vgetinventoryQuery(1,$v_data);
    $wcgoodsList = $wcgoodsList['data']['skus'];
    if(!$wcgoodsList){
        return false;
    }
    // 加锁
    require_once(ROOT_PATH . 'includes/cls_cachelock.php');
    $lock = new CacheLock('lock_order_done','lock_order_done');
    $lock->lock();
    /* 获取当前商城库存记录 */
    $sql = "SELECT gs.goods_sku, gs.locks_number, gs.goods_number, wstc.code FROM " . $ecs->table('goods_stock') . " gs LEFT JOIN " . $ecs->table('wcskutocode') . " wstc ON wstc.sku = gs.goods_sku WHERE area_id = 3";
    $goodsList = $db->getAll($sql);
    /* 获取当前未推送占用库存量 */
    $sql = "SELECT order_id FROM " . $ecs->table('order_info') . " WHERE wangcangstatus < 100 AND (order_status = 1 OR order_status = 0 OR order_status = 4) AND agency_id = 3";
    $orderList = $db->getCol($sql);
    $newArray = array();
    foreach ($orderList as $key => $value) {
        $sql = "SELECT goods_sku, goods_attr_sku, goods_number FROM " . $ecs->table('order_goods') . " WHERE order_id = $value";
        $orderGoods = $db->getAll($sql);
        if(!empty($orderGoods)){
            foreach ($orderGoods as $k => $v) {
                $sku = !empty($v['goods_attr_sku'])?$v['goods_attr_sku']:$v['goods_sku'];
                $newArray[$sku] = !empty($newArray[$sku])?($v['goods_number']+$newArray[$sku]):$v['goods_number'];
            }
        }
    }

    /* 获取当前闪购占用库存 */
    $sql = "SELECT (goods_num - buy_num) AS goods_number, goods_sku FROM " . $ecs->table('limit') . " WHERE area_id = 3 AND is_stock = 0 AND start_time >= " . time() . " AND end_time <= " . time();
    $limitList = $db->getAll($sql);
    if(!empty($limitList)){
        foreach ($limitList as $key => $value) {
            $newArray[$value['goods_sku']] = !empty($newArray[$value['goods_sku']])?($value['goods_number']+$newArray[$value['goods_sku']]):$value['goods_number'];
        }
    }
    /* 转换格式 */
    $newGoodsList = array();
    foreach ($goodsList as $key => $value) {
        $value['goods_number'] = $value['goods_number'] + $value['locks_number'];
        if(empty($value['code'])) $value['code'] = $value['goods_sku'];
        if(!empty($newArray[$value['goods_sku']])){
            $value['inStock'] = $newArray[$value['goods_sku']];
        }else{
            $value['inStock'] = 0;
        }
        $value['goods_stock'] = $value['goods_number'] + $value['inStock'];
        $newGoodsList["$value[code]"] = $value;
    }
    $goodsList = $newGoodsList;
    /* 遍历比较 */
    foreach ($wcgoodsList as $key => $value) {
        if(!empty($goodsList[$value['product_code']])){
            if($goodsList[$value['product_code']]['goods_stock'] == $value['qty_available']){
                unset($goodsList[$value['product_code']]);
            }else{
                $goodsList[$value['product_code']]['qty_available'] = $value['qty_available'];
            }
        }
    }
    /* 更新库存 */
    foreach ($goodsList as $key => $value) {
        if(isset($value['qty_available'])){
            $goods_number = $value['qty_available'] - $value['inStock'];
            $sql = "UPDATE " . $ecs->table('goods_stock') . " SET goods_number = $goods_number - locks_number WHERE goods_sku = $value[goods_sku] AND area_id = 3";
            $db->query($sql);
        }else{
            unset($goodsList[$key]);
        }
    }
    // 释放锁
    $lock->unlock();

    echo "<br/>程序结束<br/>打印结果<br/><pre>";
    print_r($goodsList);
    echo "</pre>";
    exit;
}
/* 查询并更新订单状态 */
elseif($action == 'updateOrderStatus'){
    echo '程序开始<br/>';
    /* 获取查询的订单 */
    $data = vgettradeStatusQuery(false, $v_data, 1, date('Y-m-d H:i:s', time()-86400), date('Y-m-d H:i:s'));
    if(!empty($data['data']['trades'])) $data = $data['data']['trades'];
        else $data = false;
    if(!empty($data)){
        foreach ($data as $key => $value) {
            $sql = "SELECT order_status, pay_status, shipping_status, shipping_time FROM " . $ecs->table('order_info') . " WHERE order_sn = '$value[order_no]'";
            $o = $db->getRow($sql);
            $update = '';
            if($value['status'] == 600 && ($o['order_status'] != 5 || $o['shipping_status'] != 2 || $o['pay_status'] != 2)){
                $update = 'order_status = 5, shipping_status = 2, pay_status=2,';
            }
            if($value['status'] == 500 && ($o['order_status'] != 5 || $o['shipping_status'] != 1)){
                $update = 'order_status = 5, shipping_status = 1, invoice_no = '. $value['out_ids'] . ", shipping_time = " . time() . ", ";
                if(!empty($value['transporter_id'])){
                    $update .= "wcShippingId = $value[transporter_id], ";
                }
            }
            $sql = "UPDATE " . $ecs->table('order_info') . " SET $update wangcangstatus = $value[status] WHERE order_sn = '$value[order_no]' AND order_status != 2";
            $db->query($sql);
        }
    }
    echo "<br/>程序结束<br/>打印结果<br/><pre>";
    print_r($data);
    echo "</pre>";
    exit;
}
/* 处理订单队列 */
elseif ($action == 'queueToOrder') {
    require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/user.php');
    require_once(ROOT_PATH . 'languages/' .$_CFG['lang']. '/shopping_flow.php');
    include_once(ROOT_PATH . 'includes/classQueue.php');
    $q = new classQueue;
    include_once(ROOT_PATH . 'includes/classCounter.php');
    $c = new classCounter;
    include_once(ROOT_PATH . 'includes/classOrder.php');
    $cOrder = new classOrder;
    $orderSum = $c->getCounter('orderDoneSum'); // 当前订单总号
    $orderSumNow = $c->getCounter('orderDoneSumNow'); // 已处理订单
    if (empty($orderSumNow) && $orderSumNow === false) {
        $orderSumNow = 0;
        $c->addCounter('orderDoneSumNow');
    }
    if (empty($orderSum) && $orderSum === false) {
        $orderSum = 0;
        $c->addCounter('orderDoneSum');
    }
    if (isset($orderSum) && isset($orderSumNow) && $orderSum > $orderSumNow) {
        // 存在队列订单
        $x = $GLOBALS['_CFG']['orderQueueMax'] - $orderSum%$GLOBALS['_CFG']['orderQueueMax'];// 查看还有多少订单才满队
        if ($x != $GLOBALS['_CFG']['orderQueueMax']) {
            // 当前队列有且不满的情况下，填满，方便下一次处理队列时不会出现数据错误
            $c->inCounter('orderDoneSum', $x); // 让当前处理的队进行满队处理
        }
        $y = intval($orderSum/$GLOBALS['_CFG']['orderQueueMax']); // 当前最大队列编号
        $z = intval($orderSumNow/$GLOBALS['_CFG']['orderQueueMax']); // 当前应当处理的队列开始编号值
        if ($y - $z > 0) {
            $c->inCounter('orderDoneSumNow', ($y - $z) * $GLOBALS['_CFG']['orderQueueMax']);
            // 将需要处理的队列编号转成数组
            for ($i=$z; $i < $y; $i++) {
                $arr[] = 'orderDoneQueue' . $i;
            }
            // 读取队列数据
            foreach ($arr as $key => $value) {
                $data[$value] = $q->get($value);
            }
            // 处理订单信息
            foreach ($data as $key => $value) {
                foreach ($value as $k => $v) {
                    $result = $cOrder->orderDone($v['orderInfo'], $v['goodsList'], true);
                    if (empty($result) || $result['error'] > 0) {
                        // 订单处理不成功
                        $q->append('orderDoneErrLog', $value);
                    } else {
                        $q->append('orderDoneLog', $cOrder->orderInfo);
                    }
                }
                $q->del($key);
            }
        }
    }
    echo "<pre>";
    print_r($q->get('orderDoneLog'));
    echo "</pre>";
    exit;
}
else{
    echo '程序开始<br/>';
    vsetpushTrades(array(24632), $v_data);
    /* 推送商品信息 */
    // if(!empty($_SESSION['startnum'])) $startnum = $_SESSION['startnum'];
    // else $startnum = 0;
    // $endnum = $startnum + 10;
    // $goodsIdList = $GLOBALS['db']->getCol('SELECT goods_id FROM ' . $GLOBALS['ecs']->table('goods_stock') . " WHERE area_id = 3 AND goods_attr_id = 0 AND goods_id < $endnum AND goods_id >= $startnum GROUP BY goods_id");

// $data = vsetpushProducts(array(1684,1683,1682,1681,1793,1792,1791,1790,1789,1786,1785,1769,1744,), $v_data);

    // $data = vsetpushTrades(array('20827'), $v_data);
    // $data = vsetpushProducts($goodsIdList,$v_data);
    // if($data && ($data['count'] == '0' || $data['data']['flag'] != 'false')){
    //     $_SESSION['startnum'] = $endnum;
    // }
    // echo "请求ID范围：$startnum-".($startnum+10);

//     $sql = "SELECT order_sn FROM `egg_order_info` WHERE `wangcangstatus` = 930";
//     $order_sn = $db->getCol($sql);
//     $data = vgetcancelTrade($order_sn, $v_data);
//     foreach ($order_sn as $key => $value) {
//         $sql = "UPDATE " . $ecs->table('order_info') . " SET wangcangstatus = 0 WHERE order_sn = $value";
//         $db->query($sql);
//     }
    // $data = vgetcancelTrade(array('2015030101609'), $v_data);
    // $data = vgetinventoryQuery(array('6901893800811'),$v_data);
    echo "<br/>程序结束<br/>打印结果<br/>请求ID范围：$startnum-".($startnum+10)."<pre>";
    print_r($data);
    echo "</pre>";
    exit;
}
?>